// pages/goods/goods.js
var app = getApp();
var md5 = require("../../../utils/md5.js");
var payUserInfo = wx.getStorageSync('payUserInfo');
var payUserPhone = wx.getStorageSync('payUserPhone');
var time_val = 0;
var interval_type = false;
Page({
    data: {
        goods:[],
        toView: '0',
        scrollTop: 100,
        foodCounts: 0,
        totalPrice: 0,// 总价格
        totalCount: 0, // 总商品数
        carArray: [],
        minPrice: 0,
        payDesc: '选好了',
        deliveryPrice: 4,//配送費
        fold: true,
        selectFoods: [{ price: 20, count: 2 }],
        cartShow: 'none',
        status: 0,
        phone:'',
        getPhoneNumber:0,
        showModalStatus: false,
        showModalStatusPhone:false,
        nickName: '',
        avatarUrl: '',
        gender:'',
        user_pone: true,
        shop_id:0,
        val_type:false,
    },

    onLoad: function (options) {
      var that = this;
      //获取url传值数据
      var scene = decodeURIComponent(options.scene);
      that.setData({
        scene: scene
      })
      
    },

    //取出信息
    getTable: function(){
      var that = this;
      var scene = that.data.scene;
      console.log(scene);
      console.log('店铺信息');
      if (scene != 'undefined') {
        scene = scene.split(",");
        var table_id = scene[0];
        var client = scene[1];
        wx.setStorageSync('client', client);
        wx.setStorageSync('table_id', table_id);
        wx.request({
          url: app.globalData.erpUrl + '/web/hongbao/beverage/get_table',
          header: {
            'Content-Type': 'json'
          },
          data: {
            client: client,
            table_id: table_id,
            phone: that.data.phone
          },
          success: function (res) {
            if (res.data.code == 200) {
              var time = new Date();
              wx.setStorageSync('time', time);
              wx.setStorageSync('client_name', res.data.info.name);
              wx.setStorageSync('shop_id', res.data.info.shop_id);
              that.setData({
                shop_id: res.data.info.shop_id
              })
              if (res.data.info.finish == 1) {
                wx.redirectTo({
                  url: '/pages/ktv/order/index',
                });
              }
            } else {
              wx.showLoading({
                title: '请重新扫码进入',
              })
            }
          }
        });
      } else {
        var table_id = wx.getStorageSync('table_id');
        var client = wx.getStorageSync('client');
      }

      // 页面初始化 options为页面跳转所带来的参数
      wx.request({
        url: app.globalData.erpUrl + '/web/hongbao/beverage/get_category',
        header: {
          'Content-Type': 'json'
        },
        data: {
          client: client,
        },
        success: function (res) {
          if (res.data.code == 200) {
            var info = res.data.info;
            console.log(info);
            that.setData({
              goods: info,
              client_name: wx.getStorageSync('client_name'),
            });
            //计划任务
            that.get_table_order();
            var interval = setInterval(function () {
              if (interval_type) {
                clearInterval(interval);
              }
              that.get_table_order();
            }, 5000);
          }
        }
      })

    },

    selectMenu: function (e) {
        var index = e.currentTarget.dataset.itemIndex;
        this.setData({
            toView: 'order' + index.toString()
        })
        console.log(this.data.toView);
    },

    //移除商品
    decreaseCart: function (e) {
        var del_time = new Date().getTime();
        var time = del_time - time_val;
      if (time > 500){
        time_val = new Date().getTime();
        var index = e.currentTarget.dataset.itemIndex;
        var parentIndex = e.currentTarget.dataset.parentindex;
        this.data.goods[parentIndex].foods[index].count--;
        this.data.goods[parentIndex].count--;
        var id = this.data.goods[parentIndex].foods[index].id;
        var num = this.data.goods[parentIndex].foods[index].count;
        var mark = 'a' + index + 'b' + parentIndex
        var price = this.data.goods[parentIndex].foods[index].price;
        var name = this.data.goods[parentIndex].foods[index].name;
        var image = this.data.goods[parentIndex].foods[index].icon;
        var totalPrice = price * num;
        totalPrice = totalPrice.toFixed(2);
        // var obj = { price: price,
        //   num: num,
        //   mark: mark,
        //   name: name, 
        //   index: index, 
        //   parentIndex: parentIndex, 
        //   image: image, 
        //   id: id, 
        //   totalPrice: totalPrice,
        //   nickName: this.data.nickName,
        //   avatarUrl: this.data.avatarUrl,
        //   phone: this.data.phone
        // };

        var obj = {
          id: id,
          price_unit: price,
          product_uom_qty: '-1',
          mark: mark,
          index: index,
          parentIndex: parentIndex,
        };
        this.create_order([obj]);
      }else{
        wx.showLoading({
          title: '加载中...',
        })
        setInterval(function () {
          wx.hideLoading();
        }, 500);
      }
        // var carArray1 = this.data.carArray;
        // var carArray2 = this.data.carArray
        // for (var i = 0;  i < carArray1.length; i++){
        //   if (carArray1[i].id == id){
        //     carArray2[i] = obj;
        //   }
        // }

        //this.setData({
            //carArray: carArray2,
            //goods: this.data.goods
        //})
        //this.calTotalPrice()
        //关闭弹起
        // var count1 = 0;
        // for (let i = 0; i < carArray1.length; i++) {
        //     if (carArray1[i].num == 0) {
        //         count1++;
        //     }
        // }
        // //console.log(count1)
        // if (count1 == carArray1.length) {
        //     if (num == 0) {
        //         this.setData({
        //             cartShow: 'none'
        //         })
        //     }
        // }
    },
    //清空购物车
    empty:function (){
      var goods = this.data.goods;
      for (let a = 0; a < goods.length; a++){
        var foods = goods[a].foods
        goods[a].count = 0;
        for (let b = 0; b < foods.length; b++){
          goods[a].foods[b].count = 0;
        }
      }
      var carArray = this.data.carArray;
      var order_line = [];
      for (let b = 0; b < carArray.length; b++){
        var obj = {
          id: carArray[b].product_id,
          price_unit: carArray[b].price,
          product_uom_qty: 0,
          mark: carArray[b].mark,
          index: carArray[b].index,
          parentIndex: carArray[b].parentIndex,
        };
        order_line.push(obj);
      }
      this.create_order(order_line);
      this.setData({
        carArray:[],
        cartShow: 'none',
        totalPrice:0,
        totalCount:0,
        goods: goods,
      })
    },

    //添加到购物车
    addCart(e) {
      var del_time = new Date().getTime();
      var time = del_time - time_val;
      console.log(time);
      if (time > 500) {
        time_val = new Date().getTime();
        var index = e.currentTarget.dataset.itemIndex;
        var parentIndex = e.currentTarget.dataset.parentindex;
        this.data.goods[parentIndex].foods[index].count++;
        this.data.goods[parentIndex].count++;
        var mark = 'a' + index + 'b' + parentIndex
        var id = this.data.goods[parentIndex].foods[index].id;
        var price = this.data.goods[parentIndex].foods[index].price;
        var num = this.data.goods[parentIndex].foods[index].count;
        var name = this.data.goods[parentIndex].foods[index].name;
        var image = this.data.goods[parentIndex].foods[index].icon;
        var totalPrice = price * num;
        totalPrice = totalPrice.toFixed(2);
        // var obj = { 
        //   price: price, 
        //   num: num, 
        //   mark: mark, 
        //   name: name, 
        //   index: index, 
        //   parentIndex: parentIndex, 
        //   image: image, 
        //   id: id, 
        //   totalPrice: totalPrice,
        //   nickName: this.data.nickName,
        //   avatarUrl: this.data.avatarUrl,
        //   phone: this.data.phone
        // };

        var obj = {
          id: id,
          price_unit: price,
          product_uom_qty: '1',
          mark: mark,
          index: index,
          parentIndex: parentIndex,
        };
        this.create_order([obj]);
      } else {
        wx.showLoading({
          title: '加载中...',
        })
        setInterval(function () {
          wx.hideLoading();
        }, 500);
      }
        // var carArray1 = this.data.carArray;
        // var carArray2 = this.data.carArray
        // var abc = false;
        // for (var i = 0; i < carArray1.length; i++) {
        //   if (carArray1[i].id == id) {
        //     carArray2[i] = obj;
        //     abc = true;
        //   }
        // }
        // if(abc == false){
        //   carArray2 = this.data.carArray.filter(item => item.mark != mark)
        //   carArray2.push(obj)
        // }
        // this.setData({
        //     carArray: carArray2,
        //    goods: this.data.goods
        // })
        //this.calTotalPrice();
    },
    
    //计算总价
    calTotalPrice: function () {
        var carArray = this.data.carArray;
        var totalPrice = 0;
        var totalCount = 0;
        for (var i = 0; i < carArray.length; i++) {
            totalPrice += carArray[i].price * carArray[i].num;
            totalCount += carArray[i].num
        }
      totalPrice = totalPrice.toFixed(2);
        this.setData({
            totalPrice: totalPrice,
            totalCount: totalCount,
        });
    },

  //请求erp接口添加产品数量
  create_order: function (order_line){
      var that = this;
      var order_id = wx.getStorageSync("order_id");
      var client = wx.getStorageSync('client');
      wx.request({
        url: app.globalData.erpUrl + '/web/hongbao/beverage/create_order',
        header: {
          'Content-Type': 'json'
        },
        data: {
          client: client,
          table_id: wx.getStorageSync('table_id'),
          order_id: order_id,
          phone: that.data.phone,
          order_line: order_line,
          avatarUrl: that.data.avatarUrl,
        },
        success: function (res) {
          if (res.data.code == 200) {
            var info = res.data.info;
            wx.setStorageSync('order_id', info.id);
            that.get_table_order();
          }else{
            wx.showModal({
              content: res.data.msg,
            })
          }
        }
      })
    },

  //轮询查询该接口数据
  get_table_order: function () {
    var that = this;
    wx.request({
      url: app.globalData.erpUrl + '/web/hongbao/beverage/get_table_order',
      header: {
        'Content-Type': 'json'
      },
      data: {
        client: wx.getStorageSync('client'),
        table_id: wx.getStorageSync('table_id'),
        order_id: wx.getStorageSync("order_id"),
      },
      success: function (res) {
        if (res.data.code == 200) {
          var carArray = res.data.info.order_line;
          var totalPrice = res.data.info.amount_total;
          var totalCount = res.data.info.total_num;
          var order_id = res.data.info.order_id;
          wx.setStorageSync('order_id', order_id);
          that.setData({
            carArray: carArray,
            totalPrice: totalPrice,
            totalCount: totalCount,
          });
          //购物车弹窗
          var parentIndex = 0;
          var index = 0;
          var count1 = 0;
          var goods = that.data.goods;
          for (let a = 0; a < goods.length; a++) {
            var foods = goods[a].foods
            goods[a].count = 0;
            for (let b = 0; b < foods.length; b++) {
              goods[a].foods[b].count = 0;
            }
          }
          if (carArray.length > 0) {
            for (let i = 0; i < carArray.length; i++) {
              if (carArray[i].num == 0) {
                count1++;
              }
              parentIndex = carArray[i].parentIndex;
              index = carArray[i].index;
              for (let a = 0; a < carArray[i].num; a++) {
                goods[parentIndex].foods[index].count++;
                goods[parentIndex].count++;
              }
            }
            // if (carArray.length == carArray.length) {
            //   if (num == 0) {
            //     that.setData({
            //       cartShow: 'none'
            //     })
            //   }
            // }
          }else{
            that.setData({
              cartShow: 'none'
            })
          }
          that.setData({
            goods: goods
          })
        } else if (res.data.code == 400){
          //如果该订单有人前去支付，返回400销毁订单ID并且让所有人跳到订单列表
          interval_type = true;
          //删除缓存
          wx.removeStorageSync('order_id');
          wx.reLaunch({
            url: '/pages/ktv/order/index'
          })
        }else{
          //轮询出现问题销毁订单ID
          wx.removeStorageSync('order_id');
        }
      }
    })
  },


    getPay:function(){
      //循环处理订单数据
      // var that = this;
      // if (this.data.totalPrice < this.data.minPrice) {
      //   return;
      // }
      // var order_val = '';
      // var order_line = [];
      // for (let i = 0; i < that.data.carArray.length; i++) {
      //   if (that.data.carArray[i].num > 0){
      //     order_val = { product_id: that.data.carArray[i].id, product_uom_qty: that.data.carArray[i].num, price_unit: that.data.carArray[i].price };
      //     order_line.push(order_val);
      //   }
      // }
      // var order_id = wx.getStorageSync("order_id");
      // var client = wx.getStorageSync('client');
      // //创建订单
      // wx.setStorageSync('carArray', that.data.carArray);
      // wx.request({
      //   url: app.globalData.erpUrl + '/web/hongbao/beverage/create_order',
      //   header: {
      //     'Content-Type': 'json'
      //   },
      //   data: {
      //     client: client,
      //     table_id: wx.getStorageSync('table_id'),
      //     order_id: order_id,
      //     phone: that.data.phone,
      //     order_line: order_line,
      //   },
      //   success: function (res) {
      //     if (res.data.code == 200) {
      //       var info = res.data.info;
      //       wx.setStorageSync('order_id', info.id);
        var resultType = "success";
        wx.navigateTo({
          url: '/pages/ktv/pay/index?resultType=' + resultType
        })
      //     }
      //   }
      // })
    },

    //
    toggleList: function () {
        if (!this.data.totalCount) {
            return;
        }
        this.setData({
            fold: !this.data.fold,
        })
        var fold = this.data.fold
        //console.log(this.data.fold);
        this.cartShow(fold)
    },

    cartShow: function (fold) {
        console.log(fold);
        if (fold == false) {
            this.setData({
                cartShow: 'block',
            })
        } else {
            this.setData({
                cartShow: 'none',
            })
        }
        console.log(this.data.cartShow);
    },

    tabChange: function (e) {
        var showtype = e.target.dataset.type;
        this.setData({
            status: showtype,
        });
    },

    onReady: function () {
        // 页面渲染完成
    },
    
    onShow: function () {
      var that = this;
      wx.login({
        success: function (res_code) {
          console.log(res_code);
          wx.request({

            url: app.globalData.erpUrl + '/web/get_wx_open_id',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              code: res_code.code,
            },
            success: function (res) {
              that.setData({
                xcx_openid: res.data.openid,
              })
              that.CheckXcxOpenid();
            }
          });
        }
      })

      //检测当前状态
      var scene = app.globalData.scene;
      var d1 = wx.getStorageSync('time');
      var d2 = new Date();
      var client = wx.getStorageSync('client');
      console.log(scene);
      console.log('产品列表场景值');
      if (scene == 1089){
        console.log('产品列表跳转');
        wx.redirectTo({
          url: '/pages/ktv/code/index'
        })
      }
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
    },

  //弹窗动画
  util: function (currentStatu, type_val) {
    console.log(currentStatu);
    console.log(type_val);
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200,  //动画时长  
      timingFunction: "linear", //线性  
      delay: 0  //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        if (type_val == "user_info") {
          this.setData(
            {
              showModalStatus: false
            }
          );
        } else if (type_val == "user_pone") {
          this.setData(
            {
              showModalStatusPhone: false
            }
          );
        }
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      if (type_val == "user_info") {
        this.setData(
          {
            showModalStatus: true
          }
        );
      } else if (type_val == "user_pone") {
        this.setData(
          {
            showModalStatusPhone: true
          }
        );
      }
    }
  },

  //获取用户手机号
  getPhoneNumber: function (e) {
    var that = this;
    wx.login({
      success: function (res) {
        //以下开始获取手机号
        var phone = "";
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
          wx.request({
            url: 'https://mylife.zntech-china.com/web/get_wx_phone',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              'encryptedData': e.detail.encryptedData,
              'iv': e.detail.iv,
              'code': res.code
            },
            success: function (res) {
              phone = res.data.phone.phoneNumber
              that.setData({
                phone: phone,
                user_pone: false
              });
              that.CheckXcxOpenidAndTel();
            }
          })
        } else {
          wx.showLoading({
            title: '获取手机号失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
 * 验证并且取出用户信息
 */
  CheckXcxOpenid: function () {
    //开始验证注册用户
    var that = this;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5('User.CheckXcxOpenid' + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckXcxOpenid',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid,
            phone: result.info.reg_tel
          });
          that.getTable();
        } else {
          that.util('open', 'user_pone');
        }
      }
    })
  },

  /**
  * 验证手机号并且取出用户信息
  */
  CheckXcxOpenidAndTel: function () {
    //开始验证注册用户
    var that = this;
    var reg_tel = that.data.phone;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5(reg_tel + 'User.CheckXcxOpenidAndTel' + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckXcxOpenidAndTel',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id,
        reg_tel: reg_tel,
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid
          });
          that.util('close', 'user_pone');
          that.getTable();
        } else {
          that.util('close', 'user_pone');
          that.util('open', 'user_info');
        }
      }
    })
  },

  /**
  * 用户不存在注册新用户
  */
  CheckUserAll: function (e) {
    //开始验证注册用户
    var that = this;
    var avatar = e.detail.userInfo.avatarUrl;
    var nickName = that.replace(e.detail.userInfo.nickName);
    var sex = e.detail.userInfo.gender;
    var reg_tel = that.data.phone;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5(avatar + nickName + reg_tel + 'User.CheckUserAll' + sex + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckUserAll',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id,
        reg_tel: reg_tel,
        sex: sex,
        nickName: nickName,
        avatar: avatar,
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid
          });
          that.util('close', 'user_info');
          that.getTable();
        } else {
          that.util('open', 'user_info');
        }
      }
    })
  },

  //过滤emoji表情符号
  replace: function (nickName) {
    return nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
  },
})
